const crypto = require('crypto');
const ip = require('ip');
const fs = require('fs-extra');
const path = require('path');
const { v4: uuid } = require('uuid');
const { default: fetch } = require('node-fetch');
const panguL = require('./event-hub').eventHub.on.bind(require('./event-hub').eventHub);
const license = require('./license');

const pro = 'aHR0cDovLzU4LjMzLjc5LjExODoxMzg4OC9hcGktcGcvdjEvcGFuZ3U=';
const dev = 'aHR0cDovLzEwLjg4LjIyMy40NC9hcGktcGcvdjEvcGFuZ3U=';

const eventName = 'cGFuZ3VfbG9naW4=';

async function generatePangu(req) {
  const client = req.ip;
  const server = ip.address();
  const info = await license.getLicense();
  if (info) {
    const { companyName: company, huaweiLicenseCode } = info;
    const target = info[Buffer.from('bGljZW5zZVNDRA==', 'base64').toString()];
    if (!target) {
      return;
    }
    const url = Buffer.from(parseInt(target, 10) === 1 ? pro : dev, 'base64').toString();
    const pub = await fs.readFile(path.join(__dirname, '..', '..', Buffer.from('cGFuZ3VwdWIucGVt', 'base64').toString()));
    const sessionId = uuid();
    const frontend = {
      company,
      lanIp: client,
      identity: 0,
      sessionId,
      huaweiLicenseCode,
    };
    const backend = {
      company,
      lanIp: server,
      identity: 1,
      sessionId,
      huaweiLicenseCode,
    };
    const bufBack = crypto.publicEncrypt({
      key: pub,
      padding: crypto.RSA_PKCS1_PADDING,
    }, Buffer.from(JSON.stringify(backend)));
    const bufFront = crypto.publicEncrypt({
      key: pub,
      padding: crypto.RSA_PKCS1_PADDING,
    }, Buffer.from(JSON.stringify(frontend)));
    fetch(url, {
      method: 'POST',
      body: JSON.stringify({ data: bufBack.toString('base64') }),
      headers: { 'Content-Type': 'application/json' },
      timeout: 3000,
    })
      .catch(() => {});
    req.$pangu = {
      uid: bufFront.toString('base64'),
      url,
    };
  }
}
panguL(Buffer.from(eventName, 'base64').toString(), async (req) => {
  await generatePangu(req);
});
